<script setup lang="ts">
import { ElMessage, FormInstance, FormRules } from "element-plus";
import { onMounted, ref } from "vue";
import { reactive, defineProps } from "vue";
import { post } from "@/libs/request";
const props = defineProps(["close", "params"]);
const ruleForm = reactive<{
  quantity: number,
  type: "add" | "sub"
  specId: number
}>({
  quantity: 0,
  type: "add",
  specId: 0
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  quantity: [
    { required: true, message: "请输入数量", trigger: "blur" },
    { type: 'number', message: "只能输入数字", trigger: "blur" },
    { validator: checkNumberGreaterThanZero, trigger: 'blur' }
  ],
  specId: { required: true, message: "缺少规格id", trigger: "blur" }
});
function checkNumberGreaterThanZero(rule, value, callback) {
  if (value <= 0) {
    return callback(new Error('请输入大于0的数字'));
  } else {
    callback();
  }
}
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      post("goods/editStoreCount", {
        ...ruleForm,
      }).then((res) => {
        if (res.errCode == 0) {
          ElMessage.success(res.errMsg);
          props.close();
        } else {
          ElMessage.error(res.errMsg);
        }
      });
    }
  });
};
onMounted(() => {
  ruleForm.type = props.params?.type ?? "add";
  ruleForm.specId = props.params?.specId ?? 0;
})

</script>
<template>
  <div class="page">
    <div class="main">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="80">
        <el-form-item :label="ruleForm.type == 'add' ? '添加数量' : '减少数量'" prop="quantity">
          <el-input v-model.number="ruleForm.quantity" :placeholder="ruleForm.type == 'add' ? '请输入添加的库存数量' : '请输入减少的库存数量'" />
        </el-form-item>
        <el-form-item class="active">
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>